package com.yt.demo.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lzf
 */
@Slf4j
public class AccessFilter extends ZuulFilter {
    /**
     * 过滤器类型
     * pre: 在请求被路由前调用
     * routing: 在路由请求时调用
     * error: 在处理请求时发生错误时调用
     * post: 在routing和error过滤器之后调用
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤器的执行顺序，数值越小越优先
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否启用过滤
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 具体过滤逻辑
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();

        log.info("zuul接收到请求，参数:{}", request.getParameterMap());
        log.info("zuul接收到请求，参数:{}", request.getParameter("token"));

        if (request.getParameterMap().get("token") == null) {
            log.info("请求参数未包含token字段，返回");
            currentContext.setResponseStatusCode(401);
            currentContext.setSendZuulResponse(false);
            return null;
        }

        log.info("正常请求，放行");
        return null;
    }
}
